package com.example.selectdorm.service;

import com.example.selectdorm.entity.DormitoryRoom;
import com.example.selectdorm.repo.DormitoryRoomRepository;
import lombok.AllArgsConstructor;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.List;

@Service
@AllArgsConstructor
public class DormitoryRoomService {

    private final DormitoryRoomRepository dormitoryRoomRepository;

    public List<DormitoryRoom> findAllByUnitId(Long unitId) {
        return dormitoryRoomRepository.findAllByUnitId(unitId);
    }

    public List<DormitoryRoom> getRequiredRooms(Long unitId, int totalCount) {
        //自定义查询条件
        Specification<DormitoryRoom> spec = new Specification<DormitoryRoom>() {
            @Override
            public Predicate toPredicate(Root<DormitoryRoom> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                //根据属性名获取查询对象的属性
                Path<DormitoryRoom> unitIdCol = root.get("unitId");
                Path<DormitoryRoom> restBeds = root.get("restBeds");
                //相当于 where unitId = "unitId" and rest_beds >= totalCounts
                Predicate ge = criteriaBuilder.ge(restBeds.as(Integer.class), totalCount);
                Predicate eq = criteriaBuilder.equal(unitIdCol, unitId);
                return criteriaBuilder.and(eq, ge);
            }
        };
        //进行条件查询，findAll()方法中的参数即为条件
        List<DormitoryRoom> result = dormitoryRoomRepository.findAll(spec);

        return result;
    }




    public void checkIn(Long id, int number) {
        DormitoryRoom dormitoryRoom = dormitoryRoomRepository.getById(id);
        int restBeds = dormitoryRoom.getRestBeds();
        if (restBeds >= number){
            dormitoryRoom.setRestBeds(restBeds - number);
        }
        dormitoryRoomRepository.save(dormitoryRoom);
    }

}
